<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
      :limit="limit"
      :class="{ disabled: fileList.length === limit }"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览" :visible.sync="showImgDialog"
      ><img :src="showImgUrl" alt=""
    /></el-dialog>
    <el-progress
      :percentage="percentageNum"
      style="width: 180px"
      v-if="percentageShow"
    ></el-progress>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
var cos = new COS({
  SecretId: "AKIDWVSGtJrA0oOhneGdmmhkcFdpsiKisoW1", // 身份识别 ID
  SecretKey: "KRKzRfgT2NaeYP5XovqxymOnx40iCSTG", // 身份密钥
});
export default {
  name: "ImageUpload",
  props: {
    limit: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      showImgUrl: "",
      showImgDialog: false,
      fileList: [],
      currentUid: null,
      percentageShow: false,
      percentageNum: 0,
    };
  },
  methods: {
    onPreview(file) {
      this.showImgUrl = file.url;
      this.showImgDialog = true;
    },
    onRemove(file, fileList) {
      this.fileList = fileList;
    },
    onChange(file, fileList) {
      this.fileList = fileList;
      console.log("文件状态改变时", file, fileList);
    },
    beforeUpload({ size, type, uid }) {
      if (size > 1024 * 1024 * 2) {
        return this.$message.warning("图片体积不允许超过2M");
      }
      const types = [
        "image/png",
        "image/gif",
        "image/jpeg",
        "image/bmp",
        "image/gif",
      ];
      if (!types.includes(type)) {
        this.$message.warning("图片格式不正确");
        return Promise.reject();
      }
      this.currentUid = uid;
      this.percentageShow = true;
      return true;
    },
    httpRequest(data) {
      cos.putObject(
        {
          Bucket: "dyq-1314823220" /* 填入您自己的存储桶，必须字段 */,
          Region: "ap-nanjing" /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: data.file
            .name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: data.file /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */,
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData));
            this.percentageNum = progressData.percent * 100;
          },
        },
        (err, result) => {
          console.log(err || data);
          if (err) {
            return this.$message.err("上传失败");
          }
          this.fileList = this.fileList.map((item) => {
            if (item.uid === this.currentUid) {
              item.url = "http://" + result.Location;
            }
            return item;
          });
          this.percentageShow = false;
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.disabled {
  .el-upload {
    display: none;
  }
}
</style>
